import Users from "App/Models/Users";
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
import Order from "App/Models/Order";
import Redis from "@ioc:Adonis/Addons/Redis";
import Skus from "App/Models/Skus";
import Logs from "App/Models/Log";
import Database from "@ioc:Adonis/Lucid/Database";
export default class UsersController{
  /**
   * 添加用户
   * @param ctx
   */
  public async addUser(ctx: HttpContextContract) {
        this.writeLog(ctx,"addUser","添加用户信息");
        const params:any=ctx.request.body();
        const users=new Users();
        users.username = params.username;
        users.email = params.email;
        users.password = params.password;
        await users.save();
  }
  /**
   * 查询用户信息
   */
  public async listUser(ctx: HttpContextContract){
       const loginUser=ctx.session.get("loginUser");
       if(!loginUser){
          return {status:1};
       }
       this.writeLog(ctx,"addUser","查询用户信息");
       const params:any=ctx.request.body();
       const email=params.email;
       if(email){
           const users = await Users.query().where("email","like",`%${email}%`).forPage(1,10);
           const count=await Users.query().where("email","like",`%${email}%`).count("id");
           let countRes=count[0]['$extras']['count(`id`)'];
           return {result:users.map((user) => user.toJSON()),total:countRes};
       }
       const users = await Users.query().forPage(1,10);
       const count = await Users.query().count("id");
       let countRes=count[0]['$extras']['count(`id`)'];
       return {result:users.map((user) => user.toJSON()),total:countRes};
  }
  public async getUser(ctx: HttpContextContract){
      this.writeLog(ctx,"addUser","获取单个用户信息");
      const params:any=ctx.request.body();
      const username=params.username;
      if(username){
          const users = await Users.query().where("username","=",`${username}`);
          return users.map((user) => user.toJSON());
      }

  }

  /**
   * 生成用户订单
   */
   public async addOrder(ctx: HttpContextContract){
       this.writeLog(ctx,"addUser","用户下单");
       const trx = await Database.transaction()
       const params:any=ctx.request.body();
       const loginUser=ctx.session.get("loginUser");
       try {
           //创建订单后需要修改库存
           let skus=await Skus.query().where("id","=",params.skuId).forUpdate();
           let sku:any=skus[0];
           let orgStock=sku&&sku['$attributes'].stock;
           if(orgStock>0&&orgStock>=params.qty){
              let qty=orgStock-params.qty;
              await Order.create({userId:loginUser.id,skuId:params.skuId,qty:params.qty,price:params.price});
              await sku.merge({ stock: qty }).save();
              let orderInfo={
                skuId:params.skuId,
                qty:params.qty,
                price:params.price,
                skuName:params.skuName,
                username:loginUser.username
              };
              await trx.commit();
              await Redis.publish('add:order', JSON.stringify(orderInfo));
              return {status:0}
            }
        }catch (e) {
            await trx.rollback()
        }
        return {status:2}
   }
   public async unLogin(ctx: HttpContextContract){
       this.writeLog(ctx,"addUser","用户退出登录");
       ctx.session.forget("loginUser");
   }
   //根据用户查询订单
  public async listUserOrder(ctx: HttpContextContract) {
       this.writeLog(ctx, "listUserOrder", "查询我的订单列表");
       const loginUser=ctx.session.get("loginUser");
       if(!loginUser){
          return {status:1};
       }
       const params:any=ctx.request.body();
       let orders=new Array<any>();
       let count=new Array();
       if(!params.isAdmin){
           orders=await Order.query().where("userId","=",loginUser.id).orderBy('created_at','desc').forPage(params.curPage,params.pageSize);
           count=await Order.query().where("userId","=",loginUser.id).count("id");
       }else{
           orders=await Order.query().orderBy('created_at','desc').forPage(params.curPage,params.pageSize);
           count=await Order.query().count("id");
       }

       let countRes=count[0]['$extras']['count(`id`)'];
       let orderResult=orders.map((order) => order.toJSON());
       let skuIds=new Array();
       let userIds=new Array();
       orderResult.forEach(item=>{
          if(item.sku_id){
            skuIds.push(item.sku_id);
          }
          if(item.user_id){
            userIds.push(item.user_id);
          }
       })
       //根据订单中的sku数据查询sku信息
       let skus=await Skus.query().whereIn("id",skuIds);
       let users=await Users.query().whereIn("id",userIds);
       let skusRes=skus.map((sku) => sku.toJSON());
       let usersRes=users.map((user) => user.toJSON());
       orderResult.forEach(item=>{
             let curSkuItem=skusRes.find(skuItem=>skuItem.id==item.sku_id);
             let curUserItem=usersRes.find(userItem=>userItem.id==item.user_id);
             item.username=curUserItem&&curUserItem.username;
             item.skuName=curSkuItem&&curSkuItem.name;
             item.images=curSkuItem&&curSkuItem.images;
       })
       return {data:orderResult,count:countRes};
  }
  //删除订单
  public async deleteUserOrder(ctx: HttpContextContract) {
      this.writeLog(ctx, "deleteUserOrder", "客户删除订单");
      const params:any=ctx.request.body();
      let order=Order.query().where("id","in",params.ids);
      await order.delete();
  }

  /**
   * 删除用户
   */
  public async deleteUser(ctx: HttpContextContract) {
      this.writeLog(ctx, "deleteUserOrder", "删除用户");
      const params:any=ctx.request.body();
      let user=Users.query().where("id","in",params.ids);
      await user.delete();
  }
  /**
   * 分页查询用户日志
   * @param ctx
   * @param methodName
   * @param description
   */
  public async listUserLogs(ctx: HttpContextContract){
        const loginUser=ctx.session.get("loginUser");
        if(!loginUser){
          return {status:1};
        }
        let logs:Array<any>=new Array<any>();
        this.writeLog(ctx,"listUserLogs","查询用户日志");
        const params:any=ctx.request.body();
        logs = await Logs.query().orderBy('created_at','desc').forPage(params.curPage,params.pageSize);
        let res=logs.map((log) => log.toJSON());
        const count = await Logs.query().count("id");
        let countRes=count[0]['$extras']['count(`id`)'];
        return {result:res,total:countRes};
   }

  /**
   * 删除用户访问日志
   * @param ctx
   * @param methodName
   * @param description
   */
  public async deleteLogs(ctx: HttpContextContract) {
        this.writeLog(ctx, "deleteLogs", "删除日志");
        const params:any=ctx.request.body();
        let order=Logs.query().where("id","in",params.ids);
        await order.delete();
  }
   //异步记录用户访问日志
   public writeLog(ctx,methodName,description){
      const loginUser=ctx.session.get("loginUser");
      if(loginUser){
         let logInfo={username:loginUser.username,methodName:methodName,description:description};
         //Redis.publish('log:userActions', JSON.stringify(logInfo));
      }
  }
}
